import { reactive } from 'vue'
import { uploadFilePath } from '@/common/request/api'
import { fullLink, isString,nanoid,chooseImage} from '@/common/utils'
import { REQUEST_SUCCESS_CODE } from '@/env'
export const useUpdateImg = (count = 1, hoot = '') => {
	const imgList = reactive<Array<{
		id:string
		url: string
		path: string
	}>>([])
	const update = async (_count?:number) => {
		const res = await chooseImage({
			count:_count||count
		})
		if (res) {
			try {
				for (let item of res.tempFiles ) {
					let data = await uploadFilePath(item.tempFilePath);
					if (REQUEST_SUCCESS_CODE.includes(data.code)){
						if(count === 1){
							imgList.splice(0,imgList.length)
						}
						imgList.push({
							id: nanoid(),
							url: data.data.url,
							path: item.tempFilePath
						});
					}
					
				}
			} catch (e) {
				console.error(e);
			}
		}
	}
	const previewImage = (urls:Array<string| Record<string, any>>, current: number, key?: string) => {
		uni.previewImage({
			current: current,
			urls: urls.map(item => fullLink(hoot, isString(item) ? item : item[key as string]))
		})
	}
	const delImg = (index: number) => {
		imgList.splice(index, 1)
	}
	const addImgList = (data: string | string[],isReset?:Boolean) => {
		let arr: string[] = []
		if (isString(data)) {
			arr = data.split(',')
		} else {
			arr = data
		}
		if(isReset){
			imgList.splice(0,imgList.length)
		}
		arr.forEach(item => {
			imgList.push({
				id:nanoid(),
				url: item,
				path: item
			})
		})
	}

	return {
		imgList,
		update,
		previewImage,
		delImg,
		addImgList
	}
}